import 'package:changxindianzishangwu/http/base/http_urls.dart';
import 'package:changxindianzishangwu/pages/home_page.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/GenerateTestUserSig.dart';
import 'package:changxindianzishangwu/util/config.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/utils.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

class LoginImTest extends StatefulWidget {
  LoginImTest({Key key}) : super(key: key);

  @override
  _LoginImTestState createState() => _LoginImTestState();
}

class _LoginImTestState extends State<LoginImTest> {
  var loginValue;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("login"),
      ),
      body: Center(
        child: Container(
          child: Column(
            children: [
              TextField(
                onChanged: (val) {
                  loginValue = val;
                },
              ),
              InkWell(
                onTap: () {
                  print(loginValue);
                  _onLogin(loginValue);
                  Get.to(HomePage());
                },
                child: Container(
                  height: 60,
                  width: 400,
                  color: Colors.greenAccent,
                  alignment: Alignment.center,
                  child: Text("login"),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  _onLogin(String UserId) async {
    if (UserId == '') {
      return;
    }
    GenerateTestUserSig usersig = new GenerateTestUserSig(
      sdkappid: HttpUrls.imSdkAppId(),
      key: HttpUrls.key,
    );
    String pwdStr = usersig.genSig(identifier: UserId, expire: 86400);
    TencentImSDKPlugin.v2TIMManager
        .login(
      userID: UserId,
      userSig: pwdStr,
    )
        .then((res) async {
      if (res.code == 0) {
        V2TimValueCallback<List<V2TimUserFullInfo>> infos =
            await TencentImSDKPlugin.v2TIMManager
                .getUsersInfo(userIDList: [UserId]);

        if (infos.code == 0) {
          Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
        }
      }
    });
  }
}
